/**
 * Vault MySQL高并发服务 - 前端应用脚本
 * 提供系统监控、API调用、用户交互等功能
 */

// 全局配置
const AppConfig = {
    apiBaseUrl: '/api',
    refreshInterval: 30000, // 30秒
    requestTimeout: 10000,  // 10秒
    maxRetries: 3,
    version: '1.0.0'
};

// 应用状态管理
const AppState = {
    isLoading: false,
    systemStatus: null,
    runningTests: [],
    lastUpdate: null,
    connectionStatus: {
        vault: 'unknown',
        database: 'unknown'
    }
};

// 工具函数
const Utils = {
    /**
     * 格式化时间
     */
    formatTime(timestamp) {
        if (!timestamp) return '--';
        return new Date(timestamp).toLocaleString('zh-CN');
    },

    /**
     * 格式化文件大小
     */
    formatBytes(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },

    /**
     * 格式化持续时间
     */
    formatDuration(ms) {
        if (!ms) return '--';
        const seconds = Math.floor(ms / 1000);
        const minutes = Math.floor(seconds / 60);
        const hours = Math.floor(minutes / 60);
        
        if (hours > 0) {
            return `${hours}小时${minutes % 60}分钟`;
        } else if (minutes > 0) {
            return `${minutes}分钟${seconds % 60}秒`;
        } else {
            return `${seconds}秒`;
        }
    },

    /**
     * 获取状态颜色
     */
    getStatusColor(status) {
        const colors = {
            'success': 'success',
            'running': 'primary',
            'failed': 'danger',
            'warning': 'warning',
            'pending': 'secondary',
            'completed': 'success',
            'error': 'danger'
        };
        return colors[status] || 'secondary';
    },

    /**
     * 防抖函数
     */
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },

    /**
     * 节流函数
     */
    throttle(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    }
};

// API调用封装
const ApiClient = {
    /**
     * 通用请求方法
     */
    async request(url, options = {}) {
        const config = {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            timeout: AppConfig.requestTimeout,
            ...options
        };

        try {
            const response = await fetch(AppConfig.apiBaseUrl + url, config);
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const contentType = response.headers.get('content-type');
            if (contentType && contentType.includes('application/json')) {
                return await response.json();
            } else {
                return await response.text();
            }
        } catch (error) {
            console.error('API请求失败:', error);
            throw error;
        }
    },

    /**
     * GET请求
     */
    get(url) {
        return this.request(url);
    },

    /**
     * POST请求
     */
    post(url, data) {
        return this.request(url, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    },

    /**
     * PUT请求
     */
    put(url, data) {
        return this.request(url, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
    },

    /**
     * DELETE请求
     */
    delete(url) {
        return this.request(url, {
            method: 'DELETE'
        });
    }
};

// 系统监控模块
const SystemMonitor = {
    /**
     * 初始化监控
     */
    init() {
        this.updateSystemStatus();
        this.startPeriodicUpdate();
        this.bindEvents();
    },

    /**
     * 更新系统状态
     */
    async updateSystemStatus() {
        try {
            AppState.isLoading = true;
            this.showLoadingIndicator();

            const [systemStatus, systemInfo] = await Promise.all([
                ApiClient.get('/system/status'),
                ApiClient.get('/system/info')
            ]);

            AppState.systemStatus = systemStatus;
            AppState.lastUpdate = new Date();

            this.updateUI(systemStatus, systemInfo);
            this.updateConnectionStatus();
            
        } catch (error) {
            console.error('更新系统状态失败:', error);
            this.showError('获取系统状态失败: ' + error.message);
        } finally {
            AppState.isLoading = false;
            this.hideLoadingIndicator();
        }
    },

    /**
     * 更新UI显示
     */
    updateUI(systemStatus, systemInfo) {
        // 更新运行时间
        const uptimeElement = document.getElementById('uptime');
        if (uptimeElement && systemStatus.timestamp) {
            uptimeElement.textContent = '运行中';
        }

        // 更新内存使用情况
        if (systemInfo && systemInfo.memory) {
            this.updateMemoryDisplay(systemInfo.memory);
        }

        // 更新最后更新时间
        const lastUpdateElement = document.getElementById('lastUpdate');
        if (lastUpdateElement) {
            lastUpdateElement.textContent = `最后更新: ${Utils.formatTime(AppState.lastUpdate)}`;
        }
    },

    /**
     * 更新内存显示
     */
    updateMemoryDisplay(memory) {
        const memoryProgressBar = document.querySelector('.memory-progress .progress-bar');
        const memoryText = document.querySelector('.memory-text');
        
        if (memoryProgressBar && memory.usagePercentage) {
            memoryProgressBar.style.width = memory.usagePercentage + '%';
            memoryProgressBar.textContent = memory.usagePercentage + '%';
            
            // 根据使用率设置颜色
            memoryProgressBar.className = 'progress-bar';
            if (memory.usagePercentage > 80) {
                memoryProgressBar.classList.add('bg-danger');
            } else if (memory.usagePercentage > 60) {
                memoryProgressBar.classList.add('bg-warning');
            } else {
                memoryProgressBar.classList.add('bg-success');
            }
        }
        
        if (memoryText && memory.usedMemory && memory.totalMemory) {
            memoryText.textContent = `已用: ${memory.usedMemory} / 总计: ${memory.totalMemory}`;
        }
    },

    /**
     * 更新连接状态
     */
    async updateConnectionStatus() {
        try {
            // 检查Vault连接
            const vaultStatus = await ApiClient.get('/vault/test-connection');
            AppState.connectionStatus.vault = vaultStatus.success ? 'connected' : 'disconnected';
            
            // 更新Vault状态显示
            this.updateConnectionIndicator('vault', AppState.connectionStatus.vault);
            
        } catch (error) {
            AppState.connectionStatus.vault = 'error';
            this.updateConnectionIndicator('vault', 'error');
        }
    },

    /**
     * 更新连接指示器
     */
    updateConnectionIndicator(type, status) {
        const indicator = document.getElementById(`${type}Status`);
        if (!indicator) return;

        const statusConfig = {
            connected: { text: '已连接', class: 'text-success', icon: 'bi-check-circle-fill' },
            disconnected: { text: '未连接', class: 'text-danger', icon: 'bi-x-circle-fill' },
            error: { text: '错误', class: 'text-warning', icon: 'bi-exclamation-triangle-fill' },
            unknown: { text: '未知', class: 'text-secondary', icon: 'bi-question-circle-fill' }
        };

        const config = statusConfig[status] || statusConfig.unknown;
        indicator.innerHTML = `<i class="bi ${config.icon} me-1"></i>${config.text}`;
        indicator.className = config.class;
    },

    /**
     * 开始定期更新
     */
    startPeriodicUpdate() {
        setInterval(() => {
            if (!AppState.isLoading) {
                this.updateSystemStatus();
            }
        }, AppConfig.refreshInterval);
    },

    /**
     * 绑定事件
     */
    bindEvents() {
        // 刷新按钮
        const refreshBtn = document.getElementById('refreshBtn');
        if (refreshBtn) {
            refreshBtn.addEventListener('click', () => {
                this.updateSystemStatus();
            });
        }

        // 页面可见性变化
        document.addEventListener('visibilitychange', () => {
            if (!document.hidden && !AppState.isLoading) {
                this.updateSystemStatus();
            }
        });
    },

    /**
     * 显示加载指示器
     */
    showLoadingIndicator() {
        const indicators = document.querySelectorAll('.loading-indicator');
        indicators.forEach(indicator => {
            indicator.style.display = 'inline-block';
        });
    },

    /**
     * 隐藏加载指示器
     */
    hideLoadingIndicator() {
        const indicators = document.querySelectorAll('.loading-indicator');
        indicators.forEach(indicator => {
            indicator.style.display = 'none';
        });
    },

    /**
     * 显示错误信息
     */
    showError(message) {
        this.showNotification(message, 'danger');
    },

    /**
     * 显示成功信息
     */
    showSuccess(message) {
        this.showNotification(message, 'success');
    },

    /**
     * 显示通知
     */
    showNotification(message, type = 'info') {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
        notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
        notification.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;

        document.body.appendChild(notification);

        // 自动移除
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 5000);
    }
};

// 测试管理模块
const TestManager = {
    /**
     * 初始化测试管理
     */
    init() {
        this.bindEvents();
        this.updateRunningTests();
    },

    /**
     * 更新正在运行的测试
     */
    async updateRunningTests() {
        try {
            const runningTests = await ApiClient.get('/tests/running');
            AppState.runningTests = runningTests;
            
            // 更新运行中测试数量显示
            const runningTestsElement = document.getElementById('runningTests');
            if (runningTestsElement) {
                runningTestsElement.textContent = runningTests.length;
            }
            
        } catch (error) {
            console.error('获取运行中测试失败:', error);
        }
    },

    /**
     * 启动快速测试
     */
    async startQuickTest() {
        try {
            const testConfig = {
                testName: '快速性能测试',
                concurrentUsers: 10,
                durationSeconds: 60,
                queryType: 'SELECT',
                createdBy: 'system'
            };

            const result = await ApiClient.post('/tests/simple', testConfig);
            
            if (result.success) {
                SystemMonitor.showSuccess('快速测试已启动');
                this.updateRunningTests();
            } else {
                SystemMonitor.showError('启动测试失败: ' + result.message);
            }
            
        } catch (error) {
            SystemMonitor.showError('启动测试失败: ' + error.message);
        }
    },

    /**
     * 绑定事件
     */
    bindEvents() {
        // 快速测试按钮
        const quickTestBtn = document.getElementById('quickTestBtn');
        if (quickTestBtn) {
            quickTestBtn.addEventListener('click', () => {
                this.startQuickTest();
            });
        }
    }
};

// 连接测试模块
const ConnectionTester = {
    /**
     * 测试Vault连接
     */
    async testVaultConnection() {
        try {
            SystemMonitor.showLoadingIndicator();
            const result = await ApiClient.get('/vault/test-connection');
            
            const content = `
                <div class="alert alert-${result.success ? 'success' : 'danger'}">
                    <i class="bi bi-${result.success ? 'check-circle' : 'x-circle'}"></i>
                    ${result.message}
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <p><strong>延迟:</strong> ${result.latencyMs}ms</p>
                        <p><strong>时间:</strong> ${Utils.formatTime(result.timestamp)}</p>
                    </div>
                    <div class="col-md-6">
                        <p><strong>Vault URL:</strong> ${result.vaultUrl || '--'}</p>
                        <p><strong>状态:</strong> <span class="badge bg-${result.success ? 'success' : 'danger'}">${result.success ? '正常' : '异常'}</span></p>
                    </div>
                </div>
            `;
            
            this.showResult('Vault连接测试', content, result.success);
            
        } catch (error) {
            this.showResult('Vault连接测试', `<div class="alert alert-danger">测试失败: ${error.message}</div>`, false);
        } finally {
            SystemMonitor.hideLoadingIndicator();
        }
    },

    /**
     * 测试数据库连接
     */
    async testDatabaseConnections() {
        try {
            this.showResult('数据库连接测试', '<div class="text-center"><div class="spinner-border" role="status"></div><p class="mt-2">正在测试数据库连接...</p></div>');
            
            // 获取数据库统计信息
            const stats = await ApiClient.get('/databases/stats');
            
            const content = `
                <div class="alert alert-info">
                    <i class="bi bi-info-circle"></i>
                    数据库连接统计
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <p><strong>总配置数:</strong> ${stats.totalCount || 0}</p>
                        <p><strong>启用配置:</strong> ${stats.enabledCount || 0}</p>
                    </div>
                    <div class="col-md-6">
                        <p><strong>禁用配置:</strong> ${(stats.totalCount || 0) - (stats.enabledCount || 0)}</p>
                        <p><strong>测试时间:</strong> ${Utils.formatTime(new Date())}</p>
                    </div>
                </div>
                <div class="mt-3">
                    <small class="text-muted">详细的连接测试请使用API接口或管理界面进行。</small>
                </div>
            `;
            
            setTimeout(() => {
                this.showResult('数据库连接测试', content);
            }, 2000);
            
        } catch (error) {
            this.showResult('数据库连接测试', `<div class="alert alert-danger">测试失败: ${error.message}</div>`, false);
        }
    },

    /**
     * 查看系统状态
     */
    async viewSystemStatus() {
        try {
            const data = await ApiClient.get('/system/info');
            
            const content = `
                <div class="row">
                    <div class="col-md-6">
                        <h6><i class="bi bi-app"></i> 应用信息</h6>
                        <p><strong>名称:</strong> ${data.application?.name || 'Vault MySQL Service'}</p>
                        <p><strong>版本:</strong> ${data.application?.version || '1.0.0'}</p>
                        <p><strong>环境:</strong> ${data.application?.environment || 'development'}</p>
                    </div>
                    <div class="col-md-6">
                        <h6><i class="bi bi-cpu"></i> 系统信息</h6>
                        <p><strong>Java版本:</strong> ${data.system?.javaVersion || '--'}</p>
                        <p><strong>操作系统:</strong> ${data.system?.osName || '--'}</p>
                        <p><strong>处理器:</strong> ${data.system?.processors || '--'} 核</p>
                    </div>
                </div>
                <div class="mt-3">
                    <h6><i class="bi bi-memory"></i> 内存使用</h6>
                    <div class="progress mb-2">
                        <div class="progress-bar bg-${data.memory?.usagePercentage > 80 ? 'danger' : data.memory?.usagePercentage > 60 ? 'warning' : 'success'}" 
                             role="progressbar" style="width: ${data.memory?.usagePercentage || 0}%">
                            ${data.memory?.usagePercentage || 0}%
                        </div>
                    </div>
                    <small class="text-muted">已用: ${data.memory?.usedMemory || '--'} / 总计: ${data.memory?.totalMemory || '--'}</small>
                </div>
                <div class="mt-3">
                    <h6><i class="bi bi-clock"></i> 运行信息</h6>
                    <p><strong>启动时间:</strong> ${Utils.formatTime(data.runtime?.startTime)}</p>
                    <p><strong>运行时长:</strong> ${Utils.formatDuration(data.runtime?.uptime)}</p>
                </div>
            `;
            
            this.showResult('系统状态详情', content);
            
        } catch (error) {
            this.showResult('系统状态', `<div class="alert alert-danger">获取系统状态失败: ${error.message}</div>`, false);
        }
    },

    /**
     * 显示结果模态框
     */
    showResult(title, content, isSuccess = true) {
        const modal = document.getElementById('resultModal');
        if (!modal) return;

        document.getElementById('resultModalTitle').textContent = title;
        document.getElementById('resultModalBody').innerHTML = content;
        
        const bootstrapModal = new bootstrap.Modal(modal);
        bootstrapModal.show();
    }
};

// 页面导航模块
const PageNavigation = {
    /**
     * 显示数据库管理
     */
    showDatabaseManagement() {
        SystemMonitor.showNotification('数据库管理功能正在开发中，请使用API接口进行操作。', 'info');
    },

    /**
     * 显示Vault管理
     */
    showVaultManagement() {
        SystemMonitor.showNotification('Vault管理功能正在开发中，请使用API接口进行操作。', 'info');
    },

    /**
     * 显示性能测试
     */
    showPerformanceTesting() {
        SystemMonitor.showNotification('性能测试界面正在开发中，请使用API接口进行操作。', 'info');
    }
};

// 全局函数（供HTML调用）
window.testVaultConnection = () => ConnectionTester.testVaultConnection();
window.testDatabaseConnections = () => ConnectionTester.testDatabaseConnections();
window.startQuickTest = () => TestManager.startQuickTest();
window.viewSystemStatus = () => ConnectionTester.viewSystemStatus();
window.showDatabaseManagement = () => PageNavigation.showDatabaseManagement();
window.showVaultManagement = () => PageNavigation.showVaultManagement();
window.showPerformanceTesting = () => PageNavigation.showPerformanceTesting();

// 应用初始化
const App = {
    /**
     * 初始化应用
     */
    init() {
        console.log('Vault MySQL Service v' + AppConfig.version + ' 正在启动...');
        
        // 等待DOM加载完成
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => {
                this.start();
            });
        } else {
            this.start();
        }
    },

    /**
     * 启动应用
     */
    start() {
        try {
            // 初始化各个模块
            SystemMonitor.init();
            TestManager.init();
            
            // 绑定全局事件
            this.bindGlobalEvents();
            
            console.log('应用启动成功');
            
        } catch (error) {
            console.error('应用启动失败:', error);
            SystemMonitor.showError('应用启动失败: ' + error.message);
        }
    },

    /**
     * 绑定全局事件
     */
    bindGlobalEvents() {
        // 错误处理
        window.addEventListener('error', (event) => {
            console.error('全局错误:', event.error);
        });

        // 未处理的Promise拒绝
        window.addEventListener('unhandledrejection', (event) => {
            console.error('未处理的Promise拒绝:', event.reason);
        });

        // 网络状态变化
        window.addEventListener('online', () => {
            SystemMonitor.showSuccess('网络连接已恢复');
            SystemMonitor.updateSystemStatus();
        });

        window.addEventListener('offline', () => {
            SystemMonitor.showError('网络连接已断开');
        });
    }
};

// 启动应用
App.init();

// 导出模块（用于测试或其他脚本）
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        App,
        SystemMonitor,
        TestManager,
        ConnectionTester,
        ApiClient,
        Utils,
        AppConfig,
        AppState
    };
}